package com.example.multiple.config;

import com.example.multiple.properties.AllDatasourceProperties;
import com.example.multiple.properties.DatasourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2019/9/26-17:57
 * @Description
 */
@Component
public class MyDataSourceConfig {

	@Autowired
	private AllDatasourceProperties allDatasourceProperties;

	public List<MyDataSource> getDs(){
		List<MyDataSource> list = new ArrayList<>();
		for (DatasourceProperties client : allDatasourceProperties.getClients()) {
			MyDataSource dataSource = new MyDataSource();
			dataSource.setDriverClassName(client.getDriverClassName());
			dataSource.setJdbcUrl(client.getUrl());
			dataSource.setUsername(client.getUsername());
			dataSource.setPassword(client.getPassword());
			dataSource.setNickname(client.getNickname());
			list.add(dataSource);
		}
		return list;
	}


	/**
	 * 创建动态数据源
	 */
	public DynamicDataSource dynamicDataSource(){
		Map<Object, Object> targetDataSource = new HashMap<>();
		List<MyDataSource> myDataSourceList = getDs();
		for (MyDataSource ds : myDataSourceList) {
			targetDataSource.put(ds.getNickname(), ds);
		}
		DynamicDataSource dataSource = new DynamicDataSource();
		dataSource.setTargetDataSources(targetDataSource);
		//  设置默认的数据源
		dataSource.setDefaultTargetDataSource(myDataSourceList.get(0));
		return dataSource;
	}
}
